package com.itfreer.forestry.manage.token;

import com.itfreer.utils.json.JsonUtils;
import org.springframework.stereotype.Component;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.Response;

import com.itfreer.forestry.manage.token.common.LoginResponse;
import com.itfreer.forestry.manage.token.common.MinglingUrl;
import com.itfreer.sso.TokenExplain;
import com.itfreer.sso.TokenExplainResult;
import com.itfreer.utils.http.HeaderUtils;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.Map;

/**
 * 扩展明领外部接口
 */
@Component
public class MlTokenExplain implements TokenExplain {

	@Override
	public TokenExplainResult explain(String token) {
		// TODO Auto-generated method stub
		TokenExplainResult tokenExplainResult = new TokenExplainResult();
		Client client;
		try {
			client = HeaderUtils.buildClient(false);
			WebTarget target = client.target(MinglingUrl.getCheckTokenUrl());
			Response response = target.request().header("Authorization", token)
					.header("Content-Type", "application/json").buildGet().invoke();
			if (response.getStatus() == 200) {
				String resultJson = response.readEntity(String.class);
				if (resultJson == null || resultJson.equals("")) {
					return null;
				}
				Map maps = (Map)JsonUtils.toBean(resultJson, Map.class);
				if (maps.get("status").toString().equals("200") && maps.get("data") != null) {
					Map data = (Map)maps.get("data");
					// 根据用户ID获取用户名和密码
					tokenExplainResult.setUsername(data.get("loginName").toString());
					tokenExplainResult.setPassword(MinglingUrl.getUserPass());
					/*
					 * String id=login.getData().getId(); UserAuthenticationEntity user =
					 * userAuthenticationService.getEntity(id); if(user!=null) {
					 * tokenExplainResult.setUsername(user.getAccounts());
					 * tokenExplainResult.setPassword(MinglingUrl.getUserPass()); }
					 */
				}
			}
		} catch (KeyManagementException e1) {
			e1.printStackTrace();
		} catch (NoSuchAlgorithmException e1) {
			e1.printStackTrace();
		}
		return tokenExplainResult;
	}
}
